//
//  StatusCellPictureView.swift
//  Weibo10
//
//  Created by Leon on 15/10/20.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit
import SDWebImage

private let StatusCellPictureItemMargin: CGFloat = 4 * scale
let StatusCellPictureViewReusedID = "StatusCellPictureViewReusedID"

class StatusCellPictureView: UICollectionView {
    
    /// 视图模型
    var viewModel: StatusViewModel? {
        didSet{
            
            //自动计算行高
            sizeToFit()
            // 刷新数据--》解决cell的重用
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
    }

    ///  构造函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = StatusCellPictureItemMargin
        layout.minimumLineSpacing = StatusCellPictureItemMargin
        
        super.init(frame: frame, collectionViewLayout: layout)
        backgroundColor = UIColor.clearColor()
        
        // 注册cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusCellPictureViewReusedID)
        
        // 设置数据源
        dataSource = self
        
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - UICollectionViewDataSource
extension StatusCellPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusCellPictureViewReusedID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = viewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }
}

// MARK: - UIPickerViewDataSource
extension StatusCellPictureView {
    private func calcViewSize() -> CGSize {
        // 默认 3 张图片
        let itemCount = 3
        
        // colloctionView 总宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * statusCellMargin
        let itemWidth = (maxWidth - 2 * StatusCellPictureItemMargin) / CGFloat(itemCount)

        // 图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        // 2. 设置 layout 的 itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {

            var size = CGSize(width: 150, height: 120)
            
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                
                let img = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                
                size = img.size
            }
            
            // 解决图片过窄问题
            if size.width < 40 {
                
                size.width = 40
            }
            
            // 解决图片过宽 ---> 等比例放大
            if size.width  > 300 {
                
                size.height = size.height / size.width * 300
                size.width = 300
            }
            
            layout.itemSize = size
            return size
        }
        
        if count == 4 {
            
            let w = CGFloat(2 * itemWidth) + StatusCellPictureItemMargin
            return CGSize(width: w, height: w)
        }
        
        /*
        2 3     1 2     0 0
        5 6     4 5     1 1
        7 8 9   6 7 8   2 2 2
        */
        let row = (count-1) / itemCount + 1
        let w = CGFloat(itemCount) * itemWidth + CGFloat(itemCount - 1) * StatusCellPictureItemMargin
        let h = CGFloat(row) * itemWidth + CGFloat(row - 1) * StatusCellPictureItemMargin
        return CGSize(width: w, height: h)
    }
    
    
    
}

// MARK: - 配图 cell
private class StatusPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,                      // 在调用 OC 的框架时，可/必选项不严格
                options: [SDWebImageOptions.RetryFailed,    // SD 超时时长 15s，一旦超时会记入黑名单
                    SDWebImageOptions.RefreshCached])       // 如果 URL 不变，图像变
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 1. 添加控件
        contentView.addSubview(iconView)
        
        // 2. 设置布局 - 提示因为 cell 会变化，另外，不同的 cell 大小可能不一样
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var iconView: UIImageView = {
        
        let iv = UIImageView()
        
        // 填充方式 --》可以注意下,自己看到的东西
        iv.contentMode = .ScaleAspectFill
        // 需要裁减
        iv.clipsToBounds = true
        
        return iv
    }()
}


